;(function() {
'use strict';
angular.module('services.omdisplay.successRate')
	.service('successRate', SuccessRate)
	.factory('successRateServer', successRateServer)
	.service('successRateData', successRateData)
	.factory('successRateFn',successRateFn);
SuccessRate.$inject = ['successRateServer','successRateData','successRateFn'];
function SuccessRate(successRateServer, successRateData,successRateFn) {
	this.successRateServer = successRateServer;
	this.successRateData = successRateData;
	this.successRateFn = successRateFn;
}
function successRateServer(Restangular) {
	return {
		//业务线查询(查询接入渠道)
		querySuccessRate: function(params, callback) {
			Restangular.all('sas/Omdisplay/TransactionSuccessRate/querySuccessRate').post(params).then(callback);
		}
	};
}
function successRateData(CoreService) {
	return {
		getTypes: getTypes,
		getPageBindObj: getPageBindObj,
		getSendObj: getSendObj
	};
	//页面维度下拉框数据
	function getTypes() {
		return [{
			queryTypeCode: '01',
			queryTypeName: '全业务流程业务处理成功率'
		}, {
			queryTypeCode: '02',
			queryTypeName: '全业务流程系统处理成功率'
		}, {
			queryTypeCode: '03',
			queryTypeName: '省侧业务处理成功率'
		}, {
			queryTypeCode: '04',
			queryTypeName: '省侧系统处理成功率'
		}, {
			queryTypeCode: '05',
			queryTypeName: '统一支付业务处理成功率'
		}];
	}
	//页面绑定对象
	function getPageBindObj() {
		var year = new Date().getFullYear();
		var month = new Date().getMonth();
		var day = new Date().getDate() - 1;
		return {
			businessLine: '', //业务线
			provinceCode: [], //省份
			queryType: [],
			successRate: '',
			successRateName: '',
			timeType: '1',
			startTime: new Date(year, month, day),
			startQuarter: '',
			endTime: new Date(year, month, day),
			endQuarter: ''
		};
	}
	/**
	 * @function [splitQuarter]   选择季度时，页面获取的年和季度是一个字段，如开始时间为:20151
		将它分成开始年为2015，开始季度为1季度
	 * @param  {[object]} send  页面绑定对象
	 */
	function getQuarter(send) {
		var startYear = send.startTime.substring(0, 4);
		var startQuarter = send.startTime.substring(4, 5);
		var endYear = send.endTime.substring(0, 4);
		var endQuarter = send.endTime.substring(4, 5);
		send.startTime = startYear + '-01-01';
		send.endTime = endYear + '-01-01';
		send.startQuarter = startQuarter;
		send.endQuarter = endQuarter;
	}
	/**
	 * @function [getSendObj]  格式化页面绑定对象，传递后端
	 * @param  {[object]} pageBind 页面绑定对象
	 * @param {[array]} businessLines 业务线
	 */
	function getSendObj(pageBind,businessLines) {
		var sendObj = {
			businessLines: [],
			queryType: [],
			businessLineName: [],
			provinceCodes: [],
			provinceName: [],
			timeType: '',
			startTime: '',
			startQuarter: '',
			endTime: '',
			endQuarter: ''
		};
		var queryTypes = getTypes();
		if (pageBind.queryType.length === 0) {
			angular.forEach(queryTypes, function(qt) {
				sendObj.queryType.push(qt.queryTypeCode);
			});
		} else {
			sendObj.queryType = pageBind.queryType.map(function(blCode) {
				return blCode.queryTypeCode;
			});
		}
		if (pageBind.businessLine === '' || pageBind.businessLine === undefined) {
			angular.forEach(businessLines, function(bl) {
				if (sendObj.businessLines.indexOf(bl.businessLineCode) === -1) {
					sendObj.businessLines.push(bl.businessLineCode);
				}
        sendObj.businessLineName = [];
			});
		} else {
			sendObj.businessLines.push(pageBind.businessLine.businessLineCode);
      sendObj.businessLineName.push(pageBind.businessLine.businessLineName);
		}
		sendObj.provinceCodes = pageBind.provinceCode.map(function(item) {
			return item.provinceCode;
		});
		sendObj.provinceName = pageBind.provinceCode.map(function(item) {
			return item.provinceName;
		});
		sendObj.timeType = pageBind.timeType;
		//当账期为年或者月的时候，获取的时间是数字格式，转换为字符串时间格式
		if (sendObj.timeType === '5' || sendObj.timeType === '4') {
			sendObj.startTime = pageBind.startTime + '-01-01';
			sendObj.endTime = pageBind.endTime + '-01-01';
		} else {
			sendObj.startTime = pageBind.startTime;
			sendObj.endTime = pageBind.endTime;
		}
		sendObj.startTime = CoreService.dateFormat(sendObj.startTime, 'yyyy-MM-dd');
    sendObj.endTime = CoreService.dateFormat(sendObj.endTime, 'yyyy-MM-dd');
    if(sendObj.timeType === '4'){
      getQuarter(sendObj);
    }
		return sendObj;
	}
}
function successRateFn(){
	return {
		getEchartsData : getEchartsData,
		exportView : exportView,
		getSuccessRate : getSuccessRate
	};
  /**
 * @function [showEcharts] 显示echarts图
 * @param  {[object]} echartsText      echarts图标题
 * @param  {[array]} legendData        legend数据
 * @param  {[array]} echartsXAxis      echarts图x轴数据
 * @param  {[array]} echartsSeries     echarts图series数据
 */
  function showEcharts(echartsText, legendData, echartsXAxis, echartsSeries) {
    var option = {
      title: {
        text: echartsText,
        x: 'center'
      },
      animation: false,
      tooltip: {
        show: true,
        formatter: function(params) {
          var name = params.name; //年
          var seriesName = params.seriesName; //业务量
          var value = params.value; //多少笔
          return seriesName + ' </br>' + name + ':' + value + '%';
        }
      },
      dataZoom: {
        show: true,
        realtime: true
      },
      legend: {
        show: true,
        orient: 'vertical',
        data: legendData,
        x: 'right',
        y: 'center'
      },
      grid: {
        x2: 180
      },
      xAxis: [{
        type: 'category',
        data: echartsXAxis,
        axisLabel: {
          show: true,
          rotate: 52,
          textStyle: {
            color: 'black',
            fontFamily: 'sans-serif',
            fontSize: 10,
            fontStyle: 'italic',
            fontWeight: 'bold'
          }
        }
      }],
      yAxis: [{
        type: 'value',
        min: 90,
        max: 100,
        axisLabel: {
          show: true,
          formatter: '{value}%', // Template formatter!
        }
      }],
      series: echartsSeries
    };
    return option;
  }
  /**
   * @function [getEchartsData]    将后端返回的数据拼装成echarts图所需要的数据格式,并返回echarts图实例
   * @param  {[object]} provinceArr 存放了省份代码和省份名字
   * @param  {[array]} dataArr     后端返回数组
   * @param  {[string]} title      echarts图标题标题
   * @return {[type]}              echarts实例
   */
  function getEchartsData(provinceArr, dataArr, title) {
    var temp = {
      provinces:[]
    };
    var bnArr = {};
    angular.forEach(provinceArr, function(pa) {
      temp.provinces.push(pa.provinceName);
    });
    angular.forEach(dataArr, function(da) {
      bnArr[da.queryTypeName] = [];
      angular.forEach(da.lineData, function(ld,index) {
        if (temp.provinces[index] === ld.provinceName) {
          bnArr[da.queryTypeName].push(ld.processSuccessRate);
        }
      });
    });
    var echartsSeries = [];
    var legendData = [];
    for (var j in bnArr) {
      legendData.push(j);
    }
    for (var e = 0, f = legendData.length; e < f; e++) {
      echartsSeries[e] = {
        name: legendData[e],
        type: 'line',
        smooth: true,
        data: bnArr[legendData[e]]
      };
    }
    var echartsOption = showEcharts(title, legendData, temp.provinces, echartsSeries);
    return echartsOption;
  }
  //导出excel
  function exportView(send,myEcharts1) {
    var outData = {};
    var base64 = '';
    base64 = myEcharts1.getDataURL('png');
    send.base64 = base64.split(',')[1];
    outData.data = JSON.stringify(send);
    return outData;
  }
  //成功率格式化
  function fmtSuccessRate(avgSuccessRate){
    if(avgSuccessRate > 99.9999 && avgSuccessRate < 100){
      avgSuccessRate = 99.9999;
    }
    if(avgSuccessRate <= 0.0001 && avgSuccessRate !== 0){
      avgSuccessRate = 0.0001;
    }
    return avgSuccessRate;
  }
  /**
   * @function [getSuccessRate] 获取每个省份的汇总成功率.
   * @param  {[object]} result  后端返回的数据
   * @param  {[array]} provinces 省份数据
   */
  function getSuccessRate(result){
    var gather = {
      data : {}
    };
    angular.forEach(result.data, function(rd){

      gather.data[rd.queryType] = {
        sumTotal: 0,
        sumVolume: 0,
        sumFailedAmount: 0,
        successRate: 0
      };
      angular.forEach(rd.lineData, function(ld){
        gather.data[rd.queryType].sumTotal += ld.total;
        gather.data[rd.queryType].sumVolume += ld.volume;
        gather.data[rd.queryType].sumFailedAmount += ld.failedAmount;
        if (gather.data[rd.queryType].sumTotal === 0) {
          gather.data[rd.queryType].successRate = 0;
        } else if (gather.data[rd.queryType].sumFailedAmount === 0 && gather.data[rd.queryType].sumTotal !== 0) {
          gather.data[rd.queryType].successRate = 100;
        } else {
          gather.data[rd.queryType].successRate = ((1 - (gather.data[rd.queryType].sumFailedAmount / gather.data[rd.queryType].sumTotal)) * 100);
          gather.data[rd.queryType].successRate = gather.data[rd.queryType].successRate;
        }
      });
    });
    return gather;
  }
}
})();
